# -*- encoding:utf-8 -*-
"""
@作者：ven
@文件名：encrypteUtil.py
@时间：2021-11-15  13:47
@文档说明: 加密算法
"""
import hashlib
import codecs
from binascii import b2a_hex, a2b_hex

from Crypto.Cipher import AES, PKCS1_v1_5
import base64
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_v1_5 as Cipher_pksc1_v1_5

class Encrypt:


    @classmethod
    def encryptMD5(cls, inData):
        '''
        :param inData:
        :return: MD5加密
        '''
        new_md5 = hashlib.md5()
        new_md5.update(inData.encode(encoding='utf-8'))
        return new_md5.hexdigest()

    @classmethod
    def encryptAES(cls, text):

        return cls.get_base64(text)

    @classmethod
    def add_to_16(cls, text):
        '''
        如果text不足16位的倍数就用空格补足为16位
        '''
        if len(text.encode('utf-8')) % 16:
            add = 16 - (len(text.encode('utf-8')) % 16)
        else:
            add = 0
        text = text + ('\0' * add)
        return text.encode('utf-8')

    @classmethod
    def encrypt(cls, text):
        key = 'thanks,pig4cloud'.encode('utf-8')
        mode = AES.MODE_CBC
        iv = key
        text = cls.add_to_16(text)
        cryptos = AES.new(key, mode, iv)  # CBC加密需要一个十六位的key(密钥)和一个十六位iv(偏移量)
        cipher_text = cryptos.encrypt(text)
        return b2a_hex(cipher_text)  # 因为AES加密后的字符串不一定是ascii字符集的，输出保存可能存在问题，所以这里转为16进制字符串

    @classmethod
    def get_base64(cls, text):
        '''
        :param hex:
        :return: 16进制字符串转base64
        '''
        hex = cls.encrypt(text)
        b64 = codecs.encode(codecs.decode(hex, 'hex'), 'base64').decode()
        return b64

    @classmethod
    def encryptRSA(self,password):
        rsa_key="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC76TVdYCDauGbZzehroJcglhV5FFUVJ8pSeMv/UZWb0SUkupbO+L1y8HcfHLJgXhdCyHeFQDjFFwKeITD/Wt+TchKjQAg7WRvsTcyUk2ohKTDTJosVM6OgDGKGXSZ07hlZgPoHx90UgZB2fNi6sJKPrgvUFiM5WAnVy/8ll/7eEQIDAQAB"
        public_key = '-----BEGIN PUBLIC KEY-----\n'+rsa_key+'\n-----END PUBLIC KEY-----'
        cipher = Cipher_pksc1_v1_5.new(RSA.importKey(public_key))
        cipher_text = base64.b64encode(cipher.encrypt(password.encode()))
        return cipher_text.decode()



if __name__ == '__main__':

    print(Encrypt.encryptRSA('123456'))